package com.farmer.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.farmer.mapper.AdminRoleMapper;
import com.farmer.pojo.Admin;
import com.farmer.pojo.AdminRole;
import com.farmer.pojo.UserAllocation;
import com.farmer.service.AdminService;
import com.farmer.mapper.AdminMapper;
import com.farmer.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 86183
* @description 针对表【admin(管理员)】的数据库操作Service实现
* @createDate 2024-04-18 09:30:26
*/

@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;


    @Override
    public Result add(Admin admin) {

        adminMapper.insert(admin);
        return Result.ok(null);
    }

    @Override
    public Result deleteAdmin(Integer id) {
    LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(Admin::getId,id);
    Long count = adminMapper.selectCount(lambdaQueryWrapper);
    if (count==0){
        return Result.build(null,ResultCodeEnum.ADMIN_NOTEXSIST);
    }
    Admin admin = adminMapper.selectById(id);
    if (admin.getStatus().equals(0)) {
        admin.setStatus(1);
        int affactedRows = adminMapper.updateById(admin);
        if (affactedRows > 0) {
            return Result.ok(null);
        } else {
            return Result.build(null, ResultCodeEnum.FAULT);
        }
    }else return Result.build(null,303,"管理员已处于被封禁状态");
    }

  @Override
  public Result deblock(Integer id){
       LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
       lambdaQueryWrapper.eq(Admin::getId,id);
       Long count = adminMapper.selectCount(lambdaQueryWrapper);
       if (count==0){
           return Result.build(null,ResultCodeEnum.ADMIN_NOTEXSIST);
       }
       Admin admin = adminMapper.selectById(id);
       if(admin.getStatus().equals(1)){
           admin.setStatus(0);
           int affactedRows = adminMapper.updateById(admin);
           if (affactedRows>0){
               return Result.ok(null);
           }else{
               return Result.build(null,ResultCodeEnum.FAULT);
           }
       }else return Result.build(null,304,"管理员已处于解封状态");
  }

    @Override
    public Result update(Admin admin) {
        adminMapper.updateById(admin);
        return Result.ok(null);
    }


    @Override
    public Result getById(Integer id) {
        Admin admin = adminMapper.selectById(id);
        
        if (admin != null) {
            return Result.build(admin, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }

    @Override
    public Result getAll() {
        List<Admin> admins = adminMapper.selectList(null);
        if (admins!=null&&!admins.isEmpty()){
            return Result.build(admins,111,"查询成功");
        }else{
            return Result.build(null,101,"未找到匹配信息");
        }
    }

    /*
     * 根据标题模糊查询*/
    @Override
    public Result getByTitleLike(String name){
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Admin::getUsername,name);
        List<Admin> admins = adminMapper.selectList(lambdaQueryWrapper);
        if (admins!=null&&!admins.isEmpty()){
            return Result.build(admins,111,"查询成功");
        }else{
            return Result.build(null,101,"未找到匹配信息");
        }
    }
    @Override
    public Result login(@RequestBody Admin admin) {
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername,admin.getUsername());
        Admin loginAdmin = adminMapper.selectOne(lambdaQueryWrapper);
        if (loginAdmin == null){
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        if (loginAdmin.getStatus().equals(0)) {
            //对比密码
//            String password = MD5Util.encrypt(admin.getPassword());
            if (!StringUtils.isEmpty(admin.getPassword())
                    && MD5Util.encrypt(admin.getPassword()).equals(loginAdmin.getPassword())) {
                    //登陆成功
                    //跟据用户id生成token
                    String token = jwtHelper.createToken(Long.valueOf(loginAdmin.getId()));
                    // 并将token封装result返回
                    Map data = new HashMap();
                    data.put("token", token);
                    data.put("username", admin.getUsername());
                    data.put("id", String.valueOf(loginAdmin.getId()));
                    return Result.ok(data);
            }
            //密码错误
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }else return Result.build(null,900,"管理员被封禁");
    }

    @Override
    public Result getAdminInfo(String token) {
        boolean expiration = jwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null,ResultCodeEnum.NOTLOGIN);
        }

        int adminId = jwtHelper.getUserId(token).intValue();
       Admin admin = adminMapper.selectById(adminId);
        if (admin != null) {
            admin.setPassword(null);
            Map data = new HashMap();
            data.put("login",admin);
            return Result.ok(data);
        }
        return Result.build(null,ResultCodeEnum.NOTLOGIN);
    }

    @Override
    public Result checkUserName(String name) {
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername,name);
        Long count = adminMapper.selectCount(lambdaQueryWrapper);
        if (count ==0) {
            return Result.ok(null);
        }
        return Result.build(null,ResultCodeEnum.USERNAME_USED);
    }


    @Override
    public Result register(Admin admin) {
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername,admin.getUsername());
        Long count = adminMapper.selectCount(lambdaQueryWrapper);
        if (count >0) {
            return Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        admin.setPassword(MD5Util.encrypt(admin.getPassword()));
        adminMapper.insert(admin);
//        插入AdminRole表中
        Admin admin1=adminMapper.selectList(lambdaQueryWrapper.orderByDesc(Admin::getId)).stream().findFirst().orElse(null);
        AdminRole adminRole = new AdminRole();
        adminRole.setAdminId(admin1.getId());
        adminRole.setRoleId(1);
        adminRoleMapper.insert(adminRole);
        return Result.ok(null);
    }

    @Override
    public Result updatePassword(String token, String newPassword) {
        int id = jwtHelper.getUserId(token).intValue();
        Admin loginAdmin = adminMapper.selectById(id);
        if (loginAdmin == null) {
            return Result.build(null, 600, "用户不存在");
        }
        String encryptedNewPassword = MD5Util.encrypt(newPassword);
        String password = loginAdmin.getPassword();
        if (password.equals(encryptedNewPassword)) {
            return Result.build(null, 600, "新密码不能与旧密码相同");
        }
        loginAdmin.setPassword(encryptedNewPassword);
        adminMapper.updateById(loginAdmin);
        return Result.ok(null);
    }

    @Override
    public Result avatarInsert(String token, MultipartFile file) {
        try {
            String url = Upload.uploadImage(file);
            System.out.println("图片的url：" + url);
//         得到用户id
            int id = jwtHelper.getUserId(token).intValue();
//            获取登录用户
            Admin admin = adminMapper.selectById(id);
//            更新数据库
            admin.setId(id);
            admin.setAvatar(url); // 将 OSS 返回的头像 URL 存储到数据库中
            updateById(admin);
            return Result.build(url, ResultCodeEnum.SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.build(null, ResultCodeEnum.FAULT);
        }
    }

    @Override
    public Result getAvatar(Integer id){
////      得到用户id
//        int id = jwtHelper.getUserId(token).intValue();
//      获取登录对象
        Admin admin = adminMapper.selectById(id);
        return Result.ok(admin.getAvatar());
    }

    /*
    * 分页查询*/
    @Override
    public Result page(Integer pageNum, Integer pageSize){
        // 创建分页构造对象
        Page<Admin> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        IPage<Admin> result = adminMapper.selectPage(page, null);
        // 封装到统一响应体Result中
        return Result.ok(result);
    }

//    @Override
//    public void userAllocation(UserAllocation userAllocation) {
//        this.baseMapper.deleteRoleIds(userAllocation.getRoleId());
//        if (CollUtil.isNotEmpty(userAllocation.getUserIds())) {
//            this.baseMapper.insertRoleUsers(userAllocation.getRoleId(), userAllocation.getUserIds());
//        }
//    }
    @Override
    public Result userAllocation(UserAllocation userAllocation){
        adminMapper.deleteRoleIds(userAllocation.getRoleId());
        if (!(userAllocation.getUserIds().isEmpty())){
           adminMapper.insertRoleUsers(userAllocation.getRoleId(),userAllocation.getUserIds());
        }
        return  Result.ok("修改分配用户成功");
    }
}




